package chunk.model;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

import chunk.control.GameManager;
import chunk.view.MainFrame;

public class Box extends Shape {
	
	
	
	private long tan = 0 ; //the direction of box moving 
	private int xdirect = 1;//1 right  -1 left
	private int ydirect  = 1; // the same with xdirect
	private int xSpeed = 0 ;
	private int ySpeed = 0;

	public Box(int x, int y, int width, int heigth, int speed, Color color,
			GameManager gameManager) {
		super(x, y, width, heigth, speed, color, gameManager);

	}
	
	
	/**
	 * decide the xspeed and yspeed
	 */
	public void decideDirect() {

		Hero hero = getGameMananger().getMainFrame().getMyPanel().getHero();

		int hx = hero.getX() + hero.getWidth() / 2;
		int hy = hero.getY() + hero.getHeight() / 2;

		int x = getX() + getWidth() / 2;
		int y = getY() + getHeight() / 2;

		float xlength = Math.abs(hx - x);
		float ylength = Math.abs(hy - y);

		float zlength = (float) Math
				.sqrt(xlength * xlength + ylength * ylength);

		float cos = xlength / zlength;
		float sin = ylength / zlength;

		if (((hy - y) != 0) && ((hx - x) != 0)) {

			xSpeed = (int) (cos * getSpeed());
			ySpeed = (int) (sin * getSpeed());

		} else if (hy - y == 0) {

			ySpeed = 0;
			xSpeed = getSpeed();

		} else if (hx - x == 0) {
			ySpeed = getSpeed();
			xSpeed = 0;
		}

		if ((hx - x) >= 0) {
			xdirect = 1;
		} else {
			xdirect = -1;
		}

		if ((hy - y) >= 0) {
			ydirect = 1;
		} else {
			ydirect = -1;
		}


	}

	@Override
	public void move() {
		
		int x = getX();
		int y = getY();
		
		x+= xdirect*xSpeed;
		y+= ydirect*ySpeed;
		
		setX(x);
		setY(y);
		

	}

	@Override
	public void drawSelf(Graphics g) {

		isChangeDirect();
		move();
		isCrushed();
		Color c = g.getColor();
		g.setColor(this.getColor());
		g.fillOval(getX(), getY(), getWidth(), getHeight());
		g.setColor(c);
	}
	
	
	private void isCrushed() {

		GameManager GameMananger = getGameMananger();
		Rectangle rHero = GameMananger.getMainFrame().getMyPanel().getHero()
				.getRect();
		Rectangle rBox = getRect();
		if (rBox.intersects(rHero)) {
			GameMananger.setOver(true);
		}
	}
	
	private void isChangeDirect(){
		int x = getX();
		int y = getY();
		MainFrame mainFrame  = getGameMananger().getMainFrame();
		int frameWidth =mainFrame.getWidth();
		int frameHeight = mainFrame.getHeight();
		
		if(x<=0||y<=0||(x>=frameWidth-20)||y>=frameHeight-20){
			decideDirect();
		}
	}
	
	


	
	



}
